package com.bum.api.core.html;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.lang.StringUtils;

import freemarker.cache.MruCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class HtmlRender {
	Configuration	config;

	private String	templateSuffix	= ".html";
	private String	baseSource		= "";

	public HtmlRender() {
		config = new Configuration();
		config.setObjectWrapper(new DefaultObjectWrapper());
		config.setCacheStorage(new MruCacheStorage(20, 250));
	}

	public void setFolder(String path) throws IOException {
		File folder = new File("web");
		if (StringUtils.isNotBlank(path)) {
			folder = new File(folder, path);
		}

		config.setDirectoryForTemplateLoading(folder);
	}

	public Template getTemplate(String name) throws IOException {
		if (!name.endsWith(".txt")) {
			name = name + templateSuffix;
		}
		return config.getTemplate(name);
	}

	public String render(String view, HtmlModel model) {
		try {
			Template template = getTemplate(view);

			if (model == null) {
				model = new HtmlModel();
			}
			model.put("BASE_SRC", baseSource);

			StringWriter out = new StringWriter();

			template.process(model, out);
			out.flush();
			return out.toString();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	public void setTemplateSuffix(String templateSuffix) {
		this.templateSuffix = templateSuffix;
	}

	public void setBaseSource(String baseSource) {
		this.baseSource = baseSource;
	}

}
